package com.start_eternity.oasissafewalk.controller;

import cn.hutool.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.start_eternity.oasissafewalk.comment.Result;
import com.start_eternity.oasissafewalk.pojo.dto.FaceCDTO;
import com.start_eternity.oasissafewalk.pojo.dto.FaceDetectionDTO;
import io.swagger.v3.oas.annotations.tags.Tag;
import okhttp3.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;


@RestController
@RequestMapping("/FaceRecognition")
@Tag(name = "FaceRecognition", description = "人脸检测")

public class FaceRecognition {
    public static final String API_KEY = "7PZnuTQ6W64M7A0vjV7BvLZx";
    public static final String SECRET_KEY = "SVZ6b6wgRCBwMvwWZXHfmeOTAET5XN3R";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getStr("access_token");
    }
    private static String ifurlEncode(boolean urlEncode,String base64) throws UnsupportedEncodingException {
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }
    /*
    Face detection
    人脸检测
    */
    @PostMapping("/FD")
    public Result FD(@org.springframework.web.bind.annotation.RequestBody FaceDetectionDTO faceDetectionDTO) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        String base64ImageString = faceDetectionDTO.getImage();
        String s = ifurlEncode(false,base64ImageString);
        String jsonString = "{\"image\":\"" + s + "\",\"image_type\":\"BASE64\"}";

        RequestBody body = RequestBody.create(mediaType, jsonString);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();

        return Result.success(response.body().string());
    }

    //Face Comparison V3
    //人脸对比
    @PostMapping("/FC")
    public Result FC(@org.springframework.web.bind.annotation.RequestBody FaceCDTO faceCDTO) throws IOException {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        List<String> base64ImageString = faceCDTO.getImage();
        JsonArray jsonArray = new JsonArray();
        Gson gson = new Gson();

        for (String base64Image : base64ImageString) {
            String encodedImage = ifurlEncode(false, base64Image); // 确保此方法正确实现
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("image", encodedImage);
            jsonObject.addProperty("image_type", "BASE64");
            jsonArray.add(jsonObject);
        }

        String jsonBodyString = gson.toJson(jsonArray);
        System.out.println("Request Body: " + jsonBodyString); // 打印请求体以便调试
        RequestBody body = RequestBody.create(mediaType, jsonBodyString);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + getAccessToken())
                .method("POST", body)
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();

        return Result.success(response.body().string());
    }
}